/**
 * Created by guomin on 2017/5/31.
 */
var Promise = require('bluebird');
var rp = require('request-promise');
var crypto = require('crypto');
var urlencode = require('urlencode');

var db = require('../conf/mongodb');
var client = require('../conf/redis');
var Date = require('../common/dateFormat');

var send = {
  sendSms: function (data) {
    return new Promise(function (resolve, reject) {
      var date = new Date();
      var mobile = data.mobile;
      var content = urlencode(data.content);
      var cont = replaceContent(content);
      var codeStr = '9e3f6b' + mobile + cont;
      var md5 = crypto.createHash('md5');
      md5.update(codeStr);
      var code = md5.digest('hex');
      var postParams = 'sn=213254078878284&content=' + cont + '&mobiles='
          + mobile + '&code=' + code + '&extno=100064';
      var options = {
        hostname: 'api01.wangjinxintong.com',
        port: 8090,
        path: '/smsg/p/send',
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: postParams
      };
      rp(options).then(function (result) {
        console.log("sendResult_____________", result);
        if(result.status == 0){
          client.set(mobile, '0');
          client.expire(mobile, 30);
          db.messages.insert({appId:data.appId,content:decodeURI(data.content),mobile:mobile,code:data.code,taskId:result.taskId,status:-1,msg:result.msg,sendTime:date.Format('yyyy-MM-dd hh:mm:ss.S')}).then(function(insertData){
            resolve(insertData);
          }).catch(function(err){
            reject(err);
          })
        }else{
          reject(result);
        }
      }).catch(function(err){
        reject(err);
      })
    });
  }
};

function replaceContent(content) {
  //匹配%20转为+
  var re1 = /%20/g;
  var content1 = content.replace(re1, "+");
  //匹配(转为%28
  var re2 = /\(/g;
  var content2 = content1.replace(re2, "%28");
  //匹配)转为%29
  var re3 = /\)/g;
  var content3 = content2.replace(re3, "%29");
  //匹配~转为%7E
  var re4 = /\~/g;
  var content4 = content3.replace(re4, "%7E");
  //匹配'转为%27
  var re5 = /\'/g;
  var content5 = content4.replace(re5, "%27");
  //匹配*转为%2A
  var re6 = /\*/g;
  var content6 = content5.replace(re6, "%2A");
  //匹配!转为%21
  var re7 = /!/g;
  var cont = content6.replace(re7, "%21");
  return cont;
}

exports = module.exports = send;